package com.dq.jingran.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import lombok.Data;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Random;

/**
 * @project: jingran
 * @ClassName: MybatisUtils
 * @author: dq
 * @creat: 2022/9/27 19:40
 */
@Data
public class MybatisUtils {
    public static <T> List<T> getAny(BaseMapper<T> mapper, LambdaQueryWrapper<T> condition, Integer limit) {
        LambdaQueryWrapper<T> wrapper = condition;
        Integer total = mapper.selectCount(wrapper);
        if (limit == null || limit <= 0 || total == 0) {
            return Collections.emptyList();
        }
        List<T> list = Optional
                .of(limit).filter(l -> l > total)
                .map(l -> mapper.selectList(wrapper))
                .orElseGet(() -> mapper.selectList(wrapper.last("LIMIT " + new Random().nextInt(total - (limit - 1)) + "," + limit)));
        Collections.shuffle(list);
        return list;
    }
}
